package com.stylefeng.guns.rest.modular.wz.service.impl;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.stylefeng.guns.rest.common.constant.Consts;
import com.stylefeng.guns.rest.common.persistence.dao.*;
import com.stylefeng.guns.rest.common.persistence.model.*;
import com.stylefeng.guns.rest.common.util.AliyunSmsUtil;
import com.stylefeng.guns.rest.domain.ParamMap;
import com.stylefeng.guns.rest.domain.Res;
import com.stylefeng.guns.rest.enums.EnPfFile;
import com.stylefeng.guns.rest.enums.EnWzCoupon;
import com.stylefeng.guns.rest.enums.EnWzCouponMarket;
import com.stylefeng.guns.rest.enums.EnWzMapRebate;
import com.stylefeng.guns.rest.modular.auth.util.JwtTokenUtil;
import com.stylefeng.guns.rest.modular.wz.cache.CacheService;
import com.stylefeng.guns.rest.modular.wz.controller.WzShareApi;
import com.stylefeng.guns.rest.modular.wz.service.IWzCouponMarketService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stylefeng.guns.rest.modular.wz.util.AliOssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 券库表 服务实现类
 * </p>
 *
 * @author ruiyifeng123
 * @since 2019-03-21
 */
@Service
public class WzCouponMarketServiceImpl extends ServiceImpl<WzCouponMarketMapper, WzCouponMarket> implements IWzCouponMarketService {

    @Autowired
    private WzCouponMarketMapper couponMarketMapper;
    @Autowired
    private CacheService cacheService;
    @Autowired
    private WzMapRebateMapper mapRebateMapper;
    @Autowired
    private WzUserCouponMapper userCouponMapper;
    @Autowired
    private PfOpenCityMapper openCityMapper;
    @Autowired
    private WzAdvMapMapper advMapMapper;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private WzUserRebateMapper userRebateMapper;
    @Autowired
    private WzMapRebateServiceImpl mapRebateService;


    public Res add(ParamMap paramMap) throws Exception{
        Long couponId = paramMap.getLongMisValid("couponId");//券id
        int marketPrice = paramMap.getIntMisValid("marketPrice");//券库价格
        int totalNumber = paramMap.getIntMisValid("totalNumber");//数量

        WzCoupon coupon = cacheService.coupon(couponId);
        if(totalNumber <= 0){
            return Res.fail("数量必须大于0!");
        }

        int c = couponMarketMapper.selectCount(new EntityWrapper<WzCouponMarket>().eq("coupon_id",couponId).ne("status", EnWzCouponMarket.STATUS_END.getIndex()));
        if(c > 0){
            return Res.fail("不可以加入券库");
        }

        if(marketPrice >= coupon.getPrice()){
            return Res.fail("券库价必须小于原价!");
        }
        WzAdvMap advMap=cacheService.advMap(Long.parseLong(coupon.getAdvMapId()));

        WzCouponMarket couponMarket = new WzCouponMarket();
        couponMarket.setUserCode(advMap.getUserCode());
        couponMarket.setCouponId(couponId);
        couponMarket.setMarketPrice(marketPrice);//券库价
        couponMarket.setTotalNumber(totalNumber);//总数量
        couponMarket.setSurplusNumber(totalNumber);
        couponMarket.setAdvMapCategoryFirst(advMap.getAdvMapCategoryFirst());
        couponMarket.setStatus(EnWzCouponMarket.STATUS_CHECKING.getIndex());
        couponMarket.setBeginTime(coupon.getBeginTime());
        couponMarket.setEndTime(coupon.getEndTime());
        couponMarket.setCreateTime(new Date());
        couponMarket.setAdvMapId(advMap.getAdvMapId());
        int r = couponMarketMapper.insert(couponMarket);
        if(r > 0){
            if (Consts.dev.equals("false")) {
                for (String tel : Consts.AuditorTel) {
                    SendSmsResponse response = AliyunSmsUtil.sendAdminSms(tel, "有新增券库需要审核", Consts.ADMIN_TEMPLATE_CODE);
                }
            }
            return Res.success();
        }
        return Res.fail();
    }

    public Res edit(ParamMap paramMap) throws Exception{
        Long couponMarketId = paramMap.getLongMisValid("couponMarketId");//券库id
        int marketPrice = paramMap.getIntMisValid("marketPrice");//券库价格
        int totalNumber = paramMap.getIntMisValid("totalNumber");//数量

        WzCouponMarket couponMarket = couponMarketMapper.selectById(couponMarketId);//券库模型
        WzCoupon coupon = cacheService.coupon(couponMarket.getCouponId());

        int limit = (coupon.getPrice() - marketPrice)/(Integer.parseInt(Consts.rebateLimit));
        if(coupon.getPrice() <= Integer.parseInt(Consts.rebateLimit)){
            limit = 1;
        }
        if(totalNumber <= limit){
            return Res.fail("数量必须大于" + limit);
        }


        if(marketPrice >= coupon.getPrice()){
            return Res.fail("券库价必须小于原价!");
        }
        WzAdvMap advMap=cacheService.advMap(Long.parseLong(coupon.getAdvMapId()));

        couponMarket.setMarketPrice(marketPrice);//券库价
        couponMarket.setTotalNumber(totalNumber);//总数量
        couponMarket.setSurplusNumber(totalNumber);
        couponMarket.setAdvMapCategoryFirst(advMap.getAdvMapCategoryFirst());
        couponMarket.setStatus(EnWzCouponMarket.STATUS_CHECKING.getIndex());
        int r = couponMarketMapper.updateById(couponMarket);
        if(r > 0){
            if (Consts.dev.equals("false")) {
                for (String tel : Consts.AuditorTel) {
                    SendSmsResponse response = AliyunSmsUtil.sendAdminSms(tel, "有券库修改需要审核", Consts.ADMIN_TEMPLATE_CODE);
                }
            }
            return Res.success();
        }
        return Res.fail();
    }

    public Res reward(ParamMap paramMap) {
        Long couponMarketId = paramMap.getLongMisValid("couponMarketId");//券库id
        WzCouponMarket couponMarket = couponMarketMapper.selectById(couponMarketId);//券库模型
        WzCoupon coupon = cacheService.coupon(couponMarket.getCouponId());//券模型

        paramMap.put("price",coupon.getPrice());//原价
        paramMap.put("marketPrice",couponMarket.getMarketPrice());//券库价
        paramMap.put("totalNumber",couponMarket.getTotalNumber());//总数量
        paramMap.put("surplusNumber",couponMarket.getSurplusNumber());//剩余数量
        int merchantNumber = mapRebateMapper.selectCount(new EntityWrapper<WzMapRebate>().eq("coupon_market_id",couponMarket.getCouponMarketId()).ge("status", EnWzMapRebate.STATUS_RELEASE.getIndex()));
        paramMap.put("merchantNumber",merchantNumber);//商户数量
        int usedNumber = userCouponMapper.selectCount(new EntityWrapper<WzUserCoupon>().eq("coupon_market_id",couponMarket.getCouponMarketId().toString()).eq("status", EnWzCoupon.STATUS_Used.getIndex()));
        paramMap.put("usedNumber",usedNumber);//使用数量
        paramMap.put("profit",usedNumber*couponMarket.getMarketPrice());//收益
        return Res.success(paramMap);
    }

    public Res merchantReward(ParamMap paramMap) {
        int pageNum = paramMap.getIntMisValid("pageNum");
        int pageSize = paramMap.getIntMisValid("pageSize");
        Long couponMarketId = paramMap.getLongMisValid("couponMarketId");//券库id
        String sql = "adv_map_id As advMapId,sales";
        List<Map<String, Object>> mapRebateList = mapRebateMapper.selectMapsPage(new Page<>(pageNum, pageSize),new EntityWrapper<WzMapRebate>().setSqlSelect(sql).eq("coupon_market_id",couponMarketId).ge("status", EnWzMapRebate.STATUS_RELEASE.getIndex()));
        for(Map<String, Object> map : mapRebateList){
            WzAdvMap advMap = cacheService.advMap(Long.parseLong(map.get("advMapId").toString()));
            map.put("merchantName",advMap.getName());
            map.put("merchantLogo",advMap.getLogo());
        }
        return Res.success(paramMap.data(mapRebateList));
    }

    public Res list(ParamMap paramMap) {
        int pageNum = paramMap.getIntMisValid("pageNum");
        int pageSize = paramMap.getIntMisValid("pageSize");
        Long advMapId = paramMap.getLongMisValid("advMapId");//选择做活动店铺id

        String sql = "coupon_market_id As couponMarketId,coupon_id As couponId,market_price As marketPrice,surplus_number As surplusNumber";
        List<Map<String, Object>> couponMarkets = couponMarketMapper.selectMapsPage(new Page<>(pageNum, pageSize),new EntityWrapper<WzCouponMarket>().setSqlSelect(sql).ne("adv_map_id",advMapId).eq("status",EnWzCouponMarket.STATUS_RELEASE.getIndex()).gt("end_time",new Date()).gt("surplus_number",0));
        List<Map<String, Object>> couponMarketList = new ArrayList<>();
        for(Map<String, Object> map:couponMarkets){
            int c = mapRebateMapper.selectCount(new EntityWrapper<WzMapRebate>().eq("adv_map_id",advMapId).eq("coupon_market_id",Long.parseLong(map.get("couponMarketId").toString())).le("status",EnWzMapRebate.STATUS_RELEASE.getIndex()));
            if(c <= 0){
                WzCoupon coupon = cacheService.coupon(Long.parseLong(map.get("couponId").toString()));
                map.put("pic",coupon.getPic());
                map.put("advMapId",coupon.getAdvMapId());
                map.put("benefit",coupon.getBenefit());
                map.put("pic",coupon.getPic());
                map.put("rule",coupon.getRule());
                map.put("beginTime",coupon.getBeginTime());
                map.put("endTime",coupon.getEndTime());
                map.put("price", coupon.getPrice());
                map.put("logo", coupon.getLogo());
                map.put("name", coupon.getMerchantName());
                couponMarketList.add(map);
            }
        }
        return Res.success(paramMap.data(couponMarketList));
    }

    public Res rebateAdd(ParamMap paramMap) throws Exception{
        Long couponMarketId = paramMap.getLongMisValid("couponMarketId");//券库id
        Long advMapId = paramMap.getLongMisValid("advMapId");//周边店铺id
        int needShareNumber=paramMap.getIntMisValid("needShareNumber");//需分享人数

        WzCouponMarket couponMarket = couponMarketMapper.selectById(couponMarketId);//券库模型
        WzAdvMap advMap = cacheService.advMap(advMapId);//店铺模型
        WzCoupon coupon = cacheService.coupon(couponMarket.getCouponId());//券模型

        int amount = coupon.getPrice() - couponMarket.getMarketPrice();//优惠价格
        int limit = amount/(Integer.parseInt(Consts.rebateLimit));//限制人数
        if(coupon.getPrice() <= Integer.parseInt(Consts.rebateLimit)){
            limit = 1;
        }
        if(needShareNumber <=0){
            return Res.fail("分享人数不能为0！");
        }
        if(needShareNumber > limit){
            return Res.fail("最多只能分享"+limit+"人");
        }

        //新增返利模型
        WzMapRebate mapRebate = new WzMapRebate();
        mapRebate.setCouponMarketId(couponMarketId);
        mapRebate.setAdvMapId(advMap.getAdvMapId());
        mapRebate.setCouponId(couponMarket.getCouponId());
        mapRebate.setNeedShareNumber(needShareNumber);//需要分享数量
        mapRebate.setRebatePrice(couponMarket.getMarketPrice());//返利价格
        mapRebate.setAdvMapCategoryFirst(advMap.getAdvMapCategoryFirst());
        mapRebate.setBeginTime(coupon.getBeginTime());//活动开始时间
        mapRebate.setEndTime(coupon.getEndTime());//活动结束时间
        mapRebate.setStatus(EnWzMapRebate.STATUS_CHECKING.getIndex());
        mapRebate.setCreateTime(new Date());
        mapRebate.setPrice(coupon.getPrice());//原价
        mapRebate.setLimitNumber(99);//每单限购99件
        mapRebate.setPic(coupon.getPic());//活动封面
        mapRebate.setMerchantName(coupon.getMerchantName());
        mapRebate.setMerchantUserCode(advMap.getUserCode());
        mapRebate.setBenefit(coupon.getBenefit());
        mapRebate.setAdCode(advMap.getAdCode());
        mapRebate.setType(EnWzMapRebate.Type_Other_Coupon.getIndex());
        mapRebate.setMerchantLogo(coupon.getLogo());
        //生成分享文章
        String id = mapRebateService.shareLinkId(advMap,mapRebate,coupon,needShareNumber,couponMarket.getMarketPrice());
        mapRebate.setShareLink(Consts.DOMAIN_SHARE+id+".html");
        boolean b = mapRebate.insert();
        if (b) {
            if (Consts.dev.equals("false")) {
                for (String tel : Consts.AuditorTel) {
                    SendSmsResponse response = AliyunSmsUtil.sendAdminSms(tel, "有新增券库返利活动需要审核", Consts.ADMIN_TEMPLATE_CODE);
                }
            }
            return Res.success();
        } else {
            return Res.fail();
        }
    }

    public String getCityNameByAdCode(String adCode) {
        String str = "";
        String[] adCodes=adCode.split(",");
        if(adCodes.length <= 0){
            return "金坛区";
        }
        for(String a:adCodes){
            List<PfOpenCity> openCities = openCityMapper.selectList(new EntityWrapper<PfOpenCity>().eq("ad_code",a));
            if(openCities.size() > 0){
                str += openCities.get(0).getName() + " ";
            }
        }
        return str.substring(0,str.length()-1);

    }

    public Res rebateEdit(ParamMap paramMap) throws Exception{
        Long mapRebateId = paramMap.getLongMisValid("mapRebateId");
        WzMapRebate mapRebate = mapRebateMapper.selectById(mapRebateId);
        int needShareNumber=paramMap.getIntMisValid("needShareNumber");//需分享人数

        WzCoupon coupon = cacheService.coupon(mapRebate.getCouponId());
        int amount = coupon.getPrice() - mapRebate.getRebatePrice();
        int limit = amount/(Integer.parseInt(Consts.rebateLimit));
        if(coupon.getPrice() <= Integer.parseInt(Consts.rebateLimit)){
            limit = 1;
        }
        if(needShareNumber <=0){
            return Res.fail("分享人数不能为0！");
        }
        if(needShareNumber > limit){
            return Res.fail("最多只能分享"+limit+"人");
        }
        mapRebate.setNeedShareNumber(needShareNumber);
        mapRebate.setStatus(EnWzMapRebate.STATUS_CHECKING.getIndex());
        mapRebate.setMerchantLogo(coupon.getLogo());
        mapRebate.setMerchantName(coupon.getMerchantName());
        boolean b = mapRebate.updateById();
        if (b) {
            if (Consts.dev.equals("false")) {
                for (String tel : Consts.AuditorTel) {
                    SendSmsResponse response = AliyunSmsUtil.sendAdminSms(tel, "有券库返利活动修改需要审核", Consts.ADMIN_TEMPLATE_CODE);
                }
            }
            return Res.success();
        } else {
            return Res.fail();
        }
    }

    public Res            couponMarketRebateList(ParamMap paramMap) {
        int status = paramMap.getIntMisValid("status");
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        //数据统计
        int ongoingNumber = mapRebateMapper.selectCount(new EntityWrapper<WzMapRebate>().eq("type",EnWzMapRebate.Type_Other_Coupon.getIndex()).eq("merchant_user_code", userCode).le("status",EnWzMapRebate.STATUS_RELEASE.getIndex()));
        paramMap.put("ongoingNumber", ongoingNumber);//进行中
        int finishNumber = mapRebateMapper.selectCount(new EntityWrapper<WzMapRebate>().eq("type",EnWzMapRebate.Type_Other_Coupon.getIndex()).eq("merchant_user_code", userCode).gt("status", EnWzMapRebate.STATUS_RELEASE.getIndex()));
        paramMap.put("finishNumber", finishNumber);//过期

        EntityWrapper<WzMapRebate> e = new EntityWrapper<WzMapRebate>();
        e.eq("merchant_user_code", userCode).eq("type",EnWzMapRebate.Type_Other_Coupon.getIndex());
        if (status == 1) {//进行中
            e.le("status",EnWzMapRebate.STATUS_RELEASE.getIndex());
        } else if (status == 2) {//已结束
            e.gt("status", EnWzMapRebate.STATUS_RELEASE.getIndex());
        }

        String sql = "pic,map_rebate_id As mapRebateId,coupon_id As couponId,adv_map_id As advMapId,coupon_market_id As couponMarketId,reject_remark As rejectRemark,status,price,rebate_price As rebatePrice,need_share_number As needShareNumber";
        List<Map<String, Object>> mapRebateList = mapRebateMapper.selectMaps(e.setSqlSelect(sql));
        for(Map<String, Object> map : mapRebateList){
            WzAdvMap advMap = advMapMapper.selectById(Long.parseLong(map.get("advMapId").toString()));
            map.put("logo",advMap.getLogo());
            map.put("name",advMap.getName());
            WzCoupon coupon = cacheService.coupon(Long.parseLong(map.get("couponId").toString()));
            map.put("couponBenefit",coupon.getBenefit());
            map.put("couponBeginTime",coupon.getBeginTime());
            map.put("couponEndTime",coupon.getEndTime());
            map.put("couponAdvMapName",coupon.getMerchantName());
            map.put("couponAdvMapLogo",coupon.getLogo());
            //收益
            List<Map<String, Object>> profit = userCouponMapper.selectMaps(Condition.create().setSqlSelect("sum(market_rebate_profit) As profit").eq("map_rebate_id",map.get("mapRebateId").toString()).eq("status",EnWzCoupon.STATUS_Used.getIndex()));
            if(profit.get(0) == null){
                map.put("profit",0);
            }else{
                map.put("profit",profit.get(0).get("profit"));
            }
            //分享数
            List<Map<String, Object>> totalshareNumber = userRebateMapper.selectMaps(Condition.create().setSqlSelect("sum(share_number) As totalShareNumber").eq("map_rebate_id",Long.parseLong(map.get("mapRebateId").toString())));
            if(totalshareNumber.get(0) == null){
                map.put("totalShareNumber",0);
            }else{
                map.put("totalShareNumber",totalshareNumber.get(0).get("totalShareNumber"));
            }
        }
        paramMap.put("list", mapRebateList);
        return Res.success(paramMap);
    }

    public Res rebateReward(ParamMap paramMap) {
        int type = paramMap.getIntMisValid("type");//类型:1-返利活动;2-券库返利活动
        Long mapRebateId = paramMap.getLongMisValid("mapRebateId");//返利活动id
        WzMapRebate mapRebate = mapRebateMapper.selectById(mapRebateId);//返利活动模型
        //参与活动人数
        int joinNumber = userRebateMapper.selectCount(new EntityWrapper<WzUserRebate>().eq("map_rebate_id",mapRebateId).ne("status",EnWzMapRebate.USERREBATE_STATUS_Wait_Pay.getIndex()));
        paramMap.put("joinNumber",joinNumber);
        //总分享数
        List<Map<String, Object>> totalShareNumber = userRebateMapper.selectMaps(Condition.create().setSqlSelect("sum(share_number) As totalShareNumber").eq("map_rebate_id",mapRebateId));
        if(totalShareNumber.get(0) == null){
            paramMap.put("totalShareNumber",0);
        }else{
            paramMap.put("totalShareNumber",totalShareNumber.get(0).get("totalShareNumber"));
        }
        //使用数量
        int usedNumber = userCouponMapper.selectCount(new EntityWrapper<WzUserCoupon>().eq("map_rebate_id",mapRebateId.toString()).eq("status",EnWzCoupon.STATUS_Used.getIndex()));
        paramMap.put("usedNumber",usedNumber);
        paramMap.put("profit",0);
        if(type == 1){//自己的返利活动
            List<Map<String, Object>> profit = userCouponMapper.selectMaps(Condition.create().setSqlSelect("sum(price) As profit").eq("map_rebate_id",mapRebateId.toString()).eq("status",EnWzCoupon.STATUS_Used.getIndex()));
            if(profit.get(0) != null){
                paramMap.put("profit",profit.get(0).get("profit"));
            }
        }else if(type == 2){//券库返利活动
            List<Map<String, Object>> profit = userCouponMapper.selectMaps(Condition.create().setSqlSelect("sum(market_rebate_profit) As profit").eq("map_rebate_id",mapRebateId.toString()).eq("status",EnWzCoupon.STATUS_Used.getIndex()));
            if(profit.get(0) != null){
                paramMap.put("profit",profit.get(0).get("profit"));
            }
        }
        paramMap.put("status",mapRebate.getStatus());//券id
        paramMap.put("couponId",mapRebate.getCouponId());//券id
        paramMap.put("price",mapRebate.getPrice());//原价
        paramMap.put("rebatePrice",mapRebate.getRebatePrice());//底价
        paramMap.put("needShareNumber",mapRebate.getNeedShareNumber());//最多分享人数
        paramMap.put("sales",mapRebate.getSales());//已售件数
        return Res.success(paramMap);
    }
}
